package com.xingchi.tornado.storage.core.model;

import com.xingchi.tornado.core.utils.DigestUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * 文件上传DTO
 *
 * @author xingchi
 * @date 2024/4/10 20:34
 */
@Data
@EqualsAndHashCode
public class FileUploadHolder {

    /**
     * 文件名称
     */
    private String fileName;

    /**
     * 文件流
     */
    private InputStream inputStream;

    /**
     * 临时文件名称
     */
    private String tempFileName;

    /**
     * 文件字节
     */
    private byte[] bytes;

    /**
     * 用户id
     */
    private Long userId;

    public boolean isEmpty() {
        return this.inputStream == null && this.bytes == null;
    }

    public static FileUploadHolder wrap(MultipartFile file) {

        try {
            FileUploadHolder context = new FileUploadHolder();
            context.setFileName(file.getOriginalFilename());
            InputStream inputStream = file.getInputStream();
            context.setInputStream(inputStream);
            context.setBytes(file.getBytes());
            return context;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static FileUploadHolder wrap(File file) {
        try {
            FileUploadHolder context = new FileUploadHolder();

            if (!file.isFile()) {
                throw new IOException(String.format("%s 不是一个文件", file.getAbsoluteFile()));
            }

            InputStream is = Files.newInputStream(file.toPath());
            context.setFileName(file.getName());
            context.setInputStream(is);
            return context;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static FileUploadHolder wrap(InputStream inputStream, String fileName) {
        FileUploadHolder context = new FileUploadHolder();
        context.setInputStream(inputStream);
        context.setFileName(fileName);
        return context;

    }

    public static FileUploadHolder wrap(byte[] bytes, String fileName) {
        FileUploadHolder context = new FileUploadHolder();
        context.setFileName(fileName);
        context.setBytes(bytes);
        return context;
    }

}
